package pl.edu.mimuw.irs.rcp.controller.editor.report;

import java.util.List;

import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import pl.edu.mimuw.irs.core.model.analysis.History;
import pl.edu.mimuw.irs.core.model.analysis.util.EventsUtils;
import pl.edu.mimuw.irs.core.util.Pair;

public class StepsTable {

	// *** Attributes

	private History history;
	private TableViewer viewer;
	private ResultsTable resultsTable;
	private SelectionListener listener = new SelectionListener() {

		@Override
		public void widgetDefaultSelected(SelectionEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void widgetSelected(SelectionEvent e) {
			if (!(e.item instanceof TableItem)) return;
			TableItem item = (TableItem) e.item;
			if (!(item.getData() instanceof History)) return;
			History history = (History) item.getData();
			loadHistory(history);
		}
		
	};
	
	// *** Constructors

	public StepsTable(Composite parent, ResultsTable resultsTable) {
		
		this.resultsTable = resultsTable;
		
		createPartControl(parent);
	}

	// *** Methods
	
	private void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
				| SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION);
		
		Table table = viewer.getTable();
		table.setLinesVisible (true);
		table.setHeaderVisible (true);
		
		TableColumn timestampColumn = new TableColumn(table, SWT.NONE); 
		timestampColumn.setText("Timestamp"); 
		timestampColumn.setWidth(75);
		
		TableColumn eventsColumn = new TableColumn(table, SWT.NONE); 
		eventsColumn.setText("Events"); 
		eventsColumn.setWidth(400);

		//resultsTable.getViewer().addSelectionChangedListener(selectionChangedListener);
		resultsTable.getViewer().getTable().addSelectionListener(listener);
	}

	public void loadHistory(History history) {
		viewer.getTable().removeAll();
		this.history = history;
		if (history == null) return;
		
		List<Pair<String, String>> pairsList = EventsUtils.asPairsList(this.history.getChronology());
		
		for (Pair<String, String> pair : pairsList) {
			TableItem item = new TableItem(viewer.getTable(), SWT.NONE);
			item.setText(0, pair.getKey());
			item.setText(1, pair.getValue());
		}
		
		
	}
}
